import React, { useState, memo, useEffect } from 'react';
import { Table, Dialog, Button, Row } from 'tdesign-react';
import { useAppDispatch, useAppSelector } from 'modules/store';
import { selectListSelect, getList, clearPageState } from '@/modules/list-delete/select';
import SearchForm from './components/SearchForm';
import './index.module.less';
import classnames from 'classnames';
import CommonStyle from '@/styles/common.module.less';
import { useNavigate, useLocation } from 'react-router-dom';
import PubSub from 'pubsub-js'


export const SelectTable = () => {
  // 获取当前路由地址
  const location = useLocation();
  const listPath = location.pathname.split('/').pop();
  // pub-sub 发布当前的路由
  PubSub.publish('listPath', listPath);
  const dispatch = useAppDispatch();
  const pageState = useAppSelector(selectListSelect);
  const navgate = useNavigate();
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const { loading, current, pageSize, total } = pageState;
  useEffect(() => {
    dispatch(
      getList({
        pageSize: pageState.pageSize,
        current: pageState.current,
      }),
    );
    return () => {
      dispatch(clearPageState());
    };
  }, []);
  // 选择
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  // 重新处理点击操作
  function rehandleClickOp(record: any) {
    console.log(record);
  }
  // 删除
  function handleClickDelete(record: any) {
    console.log(record);
    setVisible(true);
  }
  // 关闭弹窗
  function handleClose() {
    setVisible(false);
  }
  // 状态颜色映射
  const statusColorMap = {
    approved: <span style={{ color: '#52c41a' }}>已同意</span>,
    pending: <span style={{ color: '#faad14' }}>待审批</span>,
    occupied: <span style={{ color: '#f5222d' }}>已拒绝</span>,
  };
  const reservationList = [
    {
      id: 1,
      name: '张佳宝',
      studentId: '20221514201',
      roomNumber: '1001',
      floor: '10',
      timeRange: '2025-04-09 08:00 ~ 2025-04-10 10:00',
      status: 'approved',
    },
    {
      id: 2,
      name: '李明',
      studentId: '20221514202',
      roomNumber: '1002',
      floor: '10',
      timeRange: '2025-04-11 09:00 ~ 2025-04-12 12:00',
      status: 'pending',
    },
    {
      id: 3,
      name: '王芳',
      studentId: '20221514203',
      roomNumber: '1003',
      floor: '10',
      timeRange: '2025-04-13 10:00 ~ 2025-04-14 11:00',
      status: 'occupied',
    },
  ];
  return (
    <>
      <Row justify='start' style={{ marginBottom: '20px' }}>
        <SearchForm
          onSubmit={async (value) => {
            console.log(value);
          }}
          onCancel={() => { }}
        />
      </Row>


      <Table
        loading={loading}
        data={reservationList}
        columns={[
          {
            title: '预约人',
            align: 'left',
            width: 120,
            colKey: 'name',
          },
          {
            title: '学号',
            align: 'left',
            width: 160,
            colKey: 'studentId',
          },
          {
            title: '包间号',
            align: 'center',
            width: 100,
            colKey: 'roomNumber',
          },
          {
            title: '楼层',
            align: 'center',
            width: 80,
            colKey: 'floor',
          },
          {
            title: '预约时间段',
            align: 'center',
            width: 240,
            colKey: 'timeRange',
          },
          {
            title: '状态',
            align: 'center',
            width: 100,
            colKey: 'status',
            cell({ row }) {
              return statusColorMap[row.status as keyof typeof statusColorMap] || row.status;
            },
          },
          {
            align: 'center',
            fixed: 'right',
            width: 160,
            colKey: 'op',
            title: '操作',
            cell(record) {
              return (
                <>
                  <Button
                    theme='primary'
                    variant='text'
                    onClick={() => {
                      navgate('/room/approve');
                      rehandleClickOp(record);
                    }}
                    disabled={listPath === 'approveList' && record.row.status !== 'pending'}
                  >
                    {
                      listPath === 'approveList' ? '审批' : '编辑'
                    }
                  </Button>
                  <Button
                    theme='primary'
                    variant='text'
                    onClick={() => {
                      handleClickDelete(record);
                    }}
                  >
                    删除
                  </Button>
                </>
              );
            },
          },
        ]}
        rowKey='id'
        selectedRowKeys={selectedRowKeys}
        hover
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          onCurrentChange(current, pageInfo) {
            dispatch(
              getList({
                pageSize: pageInfo.pageSize,
                current: pageInfo.current,
              }),
            );
          },
          onPageSizeChange(size) {
            dispatch(
              getList({
                pageSize: size,
                current: 1,
              }),
            );
          },
        }}
      />
      <Dialog header='确认删除当前所选合同？' visible={visible} onClose={handleClose}>
        <p>删除后的所有合同信息将被清空,且无法恢复</p>
      </Dialog>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
function usePubSub(): { subscribe: any; publish: any; } {
  throw new Error('Function not implemented.');
}

